import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { translateDataObject } from '../../utils/i18nDataTranslator';
import styles from './GradeManagement.module.css';

interface Student {
  id: number;
  name: string;
  studentId: string;
  className: string;
  college: string;
  marketingDepartment: string;
  grade?: string;
  major?: string;
  department?: string;
}

interface Course {
  id: number;
  name: string;
  code: string;
  teacher: string;
  teacherId: number;
}

interface Teacher {
  id: number;
  name: string;
  email: string;
}

interface ClassGradeInfo {
  id?: number;
  teachingPeriod: string;
  studySegment: string;
  className: string;
  instructor: string;
  teacher: string;
  classroom: string;
  teachingMonth: string;
  course: string;
  totalStudents: number;
  type: string;
  failCount: number;
  enrollmentRate: number;
  averageScore: number;
  examSubjects: ExamSubject[];
  actualStudentCount?: number;
  notCounted?: number;
  directPromotionCount?: number;
  promotionRate?: number;
  studentGrades?: StudentGrade[];
}

interface StudentGrade {
  id?: number;
  studentId: string;
  studentName: string;
  skills: number;
  theory: number;
  comprehensiveScore: number;
  interview: number;
  deduction: number;
  status: string;
  abnormalStatus?: string;
  remarks?: string;
}

interface ExamSubject {
  subject: string;
  writtenRatio: number;
  examRatio: number;
  interviewRatio: number;
}

const GradeManagement: React.FC = () => {
  const { t, i18n } = useTranslation('grade');
  const [students, setStudents] = useState<Student[]>([]);
  const [courses, setCourses] = useState<Course[]>([]);
  const [teachers, setTeachers] = useState<Teacher[]>([]);
  const [classes, setClasses] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchFilters, setSearchFilters] = useState({
    type: '',
    teachingPeriod: '',
    studySegment: '',
    className: ''
  });
  
  // 新增状态 - 保存原始数据（未翻译的）
  const [rawClassGradesData, setRawClassGradesData] = useState<ClassGradeInfo[]>([]);
  const [filteredClassGrades, setFilteredClassGrades] = useState<ClassGradeInfo[]>([]);
  const [showClassModal, setShowClassModal] = useState(false);
  const [showDetailModal, setShowDetailModal] = useState(false);
  const [selectedClass, setSelectedClass] = useState<ClassGradeInfo | null>(null);
  const [classGrades, setClassGrades] = useState<ClassGradeInfo[]>([]);

  // 班级成绩表单状态
  const [classFormData, setClassFormData] = useState({
    teachingPeriod: '',
    studySegment: '',
    className: '',
    instructor: '',
    teacher: '',
    classroom: '',
    teachingMonth: '',
    course: '',
    totalStudents: 0,
    type: '月考',
    failCount: 0,
    enrollmentRate: 100,
    averageScore: 0,
    notCounted: 0,
    directPromotionCount: 0,
    promotionRate: 0,
    examSubjects: [
      { subject: '', writtenRatio: 50, examRatio: 50, interviewRatio: 0 }
    ] as ExamSubject[]
  });

  // 学生成绩列表
  const [studentGrades, setStudentGrades] = useState<StudentGrade[]>([]);
  // 保存原始学生成绩数据（未翻译的）
  const [rawStudentGradesData, setRawStudentGradesData] = useState<StudentGrade[]>([]);

  const API_BASE = 'http://localhost:3001/api';

  // 获取认证头
  const getAuthHeaders = () => {
    const token = localStorage.getItem('token');
    return {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json'
    };
  };

  // 翻译班级成绩数据
  const translateClassGrades = (rawData: ClassGradeInfo[]): ClassGradeInfo[] => {
    return rawData.map(classGrade => {
      // 保存原始类型值（如果还没有保存）
      const originalType = (classGrade as any)._originalType || classGrade.type;
      
      // 翻译类型字段用于显示
      const translatedTypeObj = translateDataObject({ type: originalType }, { type: 'type' }, t, 'grade') as { type: string };
      
      // 处理学生成绩的状态翻译
      let translatedStudentGrades = classGrade.studentGrades;
      if (classGrade.studentGrades && Array.isArray(classGrade.studentGrades)) {
        const studentStatusFields = { status: 'status' };
        const translated = translateDataObject(classGrade.studentGrades, studentStatusFields, t, 'grade');
        translatedStudentGrades = Array.isArray(translated) ? translated : classGrade.studentGrades;
      }
      
      return {
        ...classGrade,
        type: translatedTypeObj.type, // 翻译后的显示值
        _originalType: originalType, // 保存原始值用于搜索
        studentGrades: translatedStudentGrades
      } as ClassGradeInfo & { _originalType?: string };
    }) as ClassGradeInfo[];
  };

  // 加载数据
const loadData = async () => {
  try {
    setLoading(true);
    
    // 并行加载所有必要数据
    const [
      studentsResponse, 
      coursesResponse, 
      teachersResponse,
      classesResponse,
      classGradesResponse
    ] = await Promise.all([
      fetch(`${API_BASE}/students/for-grades`, { headers: getAuthHeaders() }),
      fetch(`${API_BASE}/courses`, { headers: getAuthHeaders() }),
      fetch(`${API_BASE}/teachers`, { headers: getAuthHeaders() }),
      fetch(`${API_BASE}/classes/with-students`, { headers: getAuthHeaders() }),
      fetch(`${API_BASE}/class-grades`, { headers: getAuthHeaders() })
    ]);
    
    if (studentsResponse.ok) {
      const studentsData = await studentsResponse.json();
      setStudents(Array.isArray(studentsData.data) ? studentsData.data : Array.isArray(studentsData) ? studentsData : []);
    }
    
    if (coursesResponse.ok) {
      const coursesData = await coursesResponse.json();
      setCourses(Array.isArray(coursesData.data) ? coursesData.data : Array.isArray(coursesData) ? coursesData : []);
    }
    
    if (teachersResponse.ok) {
      const teachersData = await teachersResponse.json();
      setTeachers(Array.isArray(teachersData.data) ? teachersData.data : Array.isArray(teachersData) ? teachersData : []);
    }
    
    if (classesResponse.ok) {
      const classesData = await classesResponse.json();
      setClasses(Array.isArray(classesData.data) ? classesData.data : Array.isArray(classesData) ? classesData : []);
    }
    
    if (classGradesResponse.ok) {
      const classGradesData = await classGradesResponse.json();
      // 处理后端返回的数据格式，如果有 data 属性就使用它，否则尝试直接使用返回的数据
      let rawClassGrades = Array.isArray(classGradesData.data) ? classGradesData.data : Array.isArray(classGradesData) ? classGradesData : [];
      
      // 保存原始数据
      setRawClassGradesData(rawClassGrades);
      
      // 自动国际化翻译
      const translatedClassGrades = translateClassGrades(rawClassGrades);
      setClassGrades(translatedClassGrades);
    } else {
      // 如果 API 不可用，使用模拟数据
      console.warn('班级成绩API不可用，使用模拟数据');
      const mockClassGrades: ClassGradeInfo[] = [
        {
          teachingPeriod: '2025.08.25-2025.09.18',
          studySegment: '人工智能学段',
          className: '人工智能2408A',
          instructor: '马文龙',
          teacher: '曲凤才',
          classroom: '704',
          teachingMonth: '实训2',
          course: '企业级人工智能项目实训一',
          totalStudents: 17,
          type: '月考',
          failCount: 0,
          enrollmentRate: 100,
          averageScore: 86.97,
          examSubjects: [
            { subject: '企业级人工智能项目实训一', writtenRatio: 50, examRatio: 50, interviewRatio: 0 }
          ]
        },
        {
          teachingPeriod: '2025.08.25-2025.09.18',
          studySegment: '人工智能学段',
          className: '人工智能2408B',
          instructor: '朱银娟',
          teacher: '曲凤才',
          classroom: '807',
          teachingMonth: '实训2',
          course: '企业级人工智能项目实训二',
          totalStudents: 16,
          type: '月考',
          failCount: 0,
          enrollmentRate: 100,
          averageScore: 85.5,
          examSubjects: [
            { subject: '企业级人工智能项目实训二', writtenRatio: 50, examRatio: 50, interviewRatio: 0 }
          ]
        }
      ];
      setClassGrades(mockClassGrades);
    }
  } catch (error) {
    console.error('加载数据失败:', error);
    // 出错时设置空数组
    setClassGrades([]);
  } finally {
    setLoading(false);
  }
};

  // 搜索函数
  const handleSearch = () => {
    const filtered = classGrades.filter(classGrade => {
      const matchesType = !searchFilters.type || classGrade.type === searchFilters.type;
      const matchesPeriod = !searchFilters.teachingPeriod || 
                           classGrade.teachingPeriod === searchFilters.teachingPeriod;
      const matchesSegment = !searchFilters.studySegment || 
                            classGrade.studySegment === searchFilters.studySegment;
      const matchesClass = !searchFilters.className || 
                          classGrade.className === searchFilters.className;
      
      return matchesType && matchesPeriod && matchesSegment && matchesClass;
    });
    
    setFilteredClassGrades(filtered);
  };

  // 重置搜索
  const handleResetSearch = () => {
    setSearchFilters({
      type: '',
      teachingPeriod: '',
      studySegment: '',
      className: ''
    });
    // 重置后直接设置所有数据
    setFilteredClassGrades(classGrades);
  };

  // 当班级成绩数据或筛选条件改变时，自动更新筛选结果
  // 注意：过滤时使用原始值，显示时使用翻译后的值
  useEffect(() => {
    // 需要获取原始类型值用于匹配（因为 classGrades 中可能包含翻译后的值）
    // 但为了保持兼容性，我们同时检查原始值和翻译值
    const filtered = classGrades.filter(classGrade => {
      // 获取原始类型值（如果数据中有 _originalType，否则使用 type）
      const originalType = (classGrade as any)._originalType || classGrade.type;
      const displayType = classGrade.type;
      
      // 检查是否匹配：先检查原始值，再检查翻译后的值
      const matchesType = !searchFilters.type || 
                         originalType === searchFilters.type || 
                         displayType === searchFilters.type;
      const matchesPeriod = !searchFilters.teachingPeriod || 
                           classGrade.teachingPeriod === searchFilters.teachingPeriod;
      const matchesSegment = !searchFilters.studySegment || 
                            classGrade.studySegment === searchFilters.studySegment;
      const matchesClass = !searchFilters.className || 
                          classGrade.className === searchFilters.className;
      
      return matchesType && matchesPeriod && matchesSegment && matchesClass;
    });
    
    setFilteredClassGrades(filtered);
  }, [classGrades, searchFilters]);

  // 加载班级成绩数据
 // 加载班级成绩数据
const loadClassGrades = async () => {
  try {
    const response = await fetch(`${API_BASE}/class-grades`, { 
      headers: getAuthHeaders() 
    });
    
    if (response.ok) {
      const classGradesData = await response.json();
      // 处理后端返回的数据格式，如果有 data 属性就使用它，否则尝试直接使用返回的数据
      let rawClassGrades = Array.isArray(classGradesData.data) ? classGradesData.data : Array.isArray(classGradesData) ? classGradesData : [];
      
      // 保存原始数据
      setRawClassGradesData(rawClassGrades);
      
      // 自动国际化翻译
      const translatedClassGrades = translateClassGrades(rawClassGrades);
      setClassGrades(translatedClassGrades);
    } else {
      // 如果API不可用，使用模拟数据
      console.warn('班级成绩API返回错误，使用模拟数据');
      const mockClassGrades: ClassGradeInfo[] = [
        {
          teachingPeriod: '2025.08.25-2025.09.18',
          studySegment: '人工智能学段',
          className: '人工智能2408A',
          instructor: '马文龙',
          teacher: '曲凤才',
          classroom: '704',
          teachingMonth: '实训2',
          course: '企业级人工智能项目实训一',
          totalStudents: 17,
          type: '月考',
          failCount: 0,
          enrollmentRate: 100,
          averageScore: 86.97,
          examSubjects: [
            { subject: '企业级人工智能项目实训一', writtenRatio: 50, examRatio: 50, interviewRatio: 0 }
          ]
        },
        {
          teachingPeriod: '2025.08.25-2025.09.18',
          studySegment: '人工智能学段',
          className: '人工智能2408B',
          instructor: '朱银娟',
          teacher: '曲凤才',
          classroom: '807',
          teachingMonth: '实训2',
          course: '企业级人工智能项目实训二',
          totalStudents: 16,
          type: '月考',
          failCount: 0,
          enrollmentRate: 100,
          averageScore: 85.5,
          examSubjects: [
            { subject: '企业级人工智能项目实训二', writtenRatio: 50, examRatio: 50, interviewRatio: 0 }
          ]
        }
      ];
      setClassGrades(mockClassGrades);
    }
  } catch (error) {
    console.error('加载班级成绩失败:', error);
    // 出错时设置空数组
    setClassGrades([]);
  }
};

  useEffect(() => {
    loadData();
  }, []);

  // 当语言切换时，重新翻译数据
  useEffect(() => {
    if (rawClassGradesData.length > 0) {
      const translated = rawClassGradesData.map(classGrade => {
        const originalType = (classGrade as any)._originalType || classGrade.type;
        const translatedTypeObj = translateDataObject({ type: originalType }, { type: 'type' }, t, 'grade') as { type: string };
        
        let translatedStudentGrades = classGrade.studentGrades;
        if (classGrade.studentGrades && Array.isArray(classGrade.studentGrades)) {
          const studentStatusFields = { status: 'status' };
          const translated = translateDataObject(classGrade.studentGrades, studentStatusFields, t, 'grade');
          translatedStudentGrades = Array.isArray(translated) ? translated : classGrade.studentGrades;
        }
        
        return {
          ...classGrade,
          type: translatedTypeObj.type,
          _originalType: originalType,
          studentGrades: translatedStudentGrades
        } as ClassGradeInfo & { _originalType?: string };
      }) as ClassGradeInfo[];
      setClassGrades(translated);
    }
    
    // 重新翻译导入的学生成绩
    if (rawStudentGradesData.length > 0) {
      const studentStatusFields = { status: 'status' };
      const translatedGrades = translateDataObject(rawStudentGradesData, studentStatusFields, t, 'grade') as StudentGrade[];
      setStudentGrades(translatedGrades);
    }
  }, [i18n.language, rawClassGradesData, rawStudentGradesData, t]);

  // 重置班级表单
  const resetClassForm = () => {
    setClassFormData({
      teachingPeriod: '',
      studySegment: '',
      className: '',
      instructor: '',
      teacher: '',
      classroom: '',
      teachingMonth: '',
      course: '',
      totalStudents: 0,
      type: '月考',
      failCount: 0,
      enrollmentRate: 100,
      averageScore: 0,
      notCounted: 0,
      directPromotionCount: 0,
      promotionRate: 0,
      examSubjects: [
        { subject: '', writtenRatio: 50, examRatio: 50, interviewRatio: 0 }
      ]
    });
    setStudentGrades([]);
    setShowClassModal(false);
  };

  // 添加考试科目
  const handleAddExamSubject = () => {
    setClassFormData({
      ...classFormData,
      examSubjects: [
        ...classFormData.examSubjects,
        { subject: '', writtenRatio: 50, examRatio: 50, interviewRatio: 0 }
      ]
    });
  };

  // 删除考试科目
  const handleRemoveExamSubject = (index: number) => {
    setClassFormData({
      ...classFormData,
      examSubjects: classFormData.examSubjects.filter((_, i) => i !== index)
    });
  };

  // 更新考试科目
  const handleUpdateExamSubject = (index: number, field: keyof ExamSubject, value: string | number) => {
    const updatedSubjects = [...classFormData.examSubjects];
    updatedSubjects[index] = {
      ...updatedSubjects[index],
      [field]: value
    };
    setClassFormData({
      ...classFormData,
      examSubjects: updatedSubjects
    });
  };

  // 导入学生成绩
  const handleImportStudentGrades = async () => {
    const fileInput = document.createElement('input');
    fileInput.type = 'file';
    fileInput.accept = '.xlsx,.xls,.csv';
    fileInput.onchange = async (e) => {
      const file = (e.target as HTMLInputElement).files?.[0];
      if (file) {
        try {
          const formData = new FormData();
          formData.append('file', file);

          console.log('开始导入学生成绩，文件:', file.name);

          const response = await fetch(`${API_BASE}/class-grades/import-student-grades`, {
            method: 'POST',
            headers: {
              'Authorization': getAuthHeaders().Authorization
            },
            body: formData
          });

          console.log('导入响应状态:', response.status, response.statusText);

          if (!response.ok) {
            const errorText = await response.text();
            let errorMessage = '导入失败';
            
            try {
              const errorJson = JSON.parse(errorText);
              errorMessage = errorJson.error || errorJson.message || errorMessage;
              console.error('导入错误:', errorJson);
            } catch {
              errorMessage = `HTTP ${response.status}: ${errorText.substring(0, 100)}`;
              console.error('导入错误（非JSON）:', errorText);
            }
            
            alert(`${t('importFailed')}: ${errorMessage}`);
            return;
          }

          const result = await response.json();
          console.log('导入结果:', result);

          if (result.success) {
            if (result.data && result.data.studentGrades) {
              // 更新学生成绩列表
              const importedGrades = result.data.studentGrades.map((g: any) => ({
                ...g,
                comprehensiveScore: g.comprehensiveScore || calculateComprehensiveScore(g)
              }));
              
              // 保存原始数据
              setRawStudentGradesData(importedGrades);
              
              // 自动国际化导入的学生成绩状态
              const studentStatusFields = { status: 'status' };
              const translatedGrades = translateDataObject(importedGrades, studentStatusFields, t, 'grade') as StudentGrade[];
              
              setStudentGrades(translatedGrades);
              
              // 更新统计信息（总人数从导入的数据中获取）
              if (result.data.stats) {
                setClassFormData(prev => ({
                  ...prev,
                  notCounted: result.data.stats.notCounted,
                  failCount: result.data.stats.failCount,
                  directPromotionCount: result.data.stats.directPromotionCount,
                  averageScore: result.data.stats.averageScore,
                  promotionRate: result.data.stats.promotionRate,
                  totalStudents: result.data.stats.total // 总人数从导入的Excel数据中获取
                }));
              }
              
              alert(t('importStudentGradesCount', { count: result.data.studentGrades.length }));
            } else {
              alert(t('importSuccessNoData'));
            }
          } else {
            throw new Error(result.error || t('importFailed'));
          }
        } catch (error) {
          console.error('导入失败:', error);
          alert(`${t('importFailed')}: ${error instanceof Error ? error.message : '未知错误'}`);
        }
      }
    };
    fileInput.click();
  };

  // 打开班级成绩创建表单
  const handleCreateClassGrade = () => {
    resetClassForm();
    setShowClassModal(true);
  };

  // 查看详情
  const handleViewDetail = (classGrade: ClassGradeInfo) => {
    // 确保详情显示的数据是已翻译的
    // 如果数据中已经有翻译，直接使用；否则实时翻译
    const classGradeWithTranslation = translateClassGrades([classGrade])[0];
    setSelectedClass(classGradeWithTranslation);
    setShowDetailModal(true);
  };

  // 当班级改变时，自动填充相关信息（讲师、导员、教室号）
  useEffect(() => {
    if (classFormData.className) {
      const selectedClass = classes.find(cls => cls.className === classFormData.className);
      if (selectedClass) {
        // 优先使用班级数据中的教室号，如果没有则从已有的班级成绩数据中查找
        const existingClassGrade = classGrades.find(cg => cg.className === classFormData.className);
        const classroomValue = selectedClass.classroom || existingClassGrade?.classroom;
        
        setClassFormData(prev => ({
          ...prev,
          // 不设置totalStudents，总人数从导入的Excel数据中获取
          instructor: selectedClass.lecturer || prev.instructor,
          teacher: selectedClass.counselor || prev.teacher,
          // 如果班级有教室号则使用，否则保持原值
          classroom: classroomValue || prev.classroom
        }));
      }
    }
  }, [classFormData.className, classes, classGrades]);

  // 计算综合成绩的函数
  const calculateComprehensiveScore = (grade: StudentGrade): number => {
    if (classFormData.examSubjects.length > 0 && classFormData.examSubjects[0].subject.trim() !== '') {
      const firstSubject = classFormData.examSubjects[0];
      const writtenRatio = firstSubject.writtenRatio / 100;
      const examRatio = firstSubject.examRatio / 100;
      const interviewRatio = firstSubject.interviewRatio / 100;
      
      // 理论成绩对应笔试，技能成绩对应机试
      const comprehensiveScore = 
        (grade.theory * writtenRatio) + 
        (grade.skills * examRatio) + 
        (grade.interview * interviewRatio) - 
        grade.deduction;
      
      return Math.max(0, Math.round(comprehensiveScore * 100) / 100);
    }
    // 如果没有配置考试科目，使用技能和理论的平均值减去扣分
    return Math.max(0, Math.round(((grade.skills + grade.theory) / 2 - grade.deduction) * 100) / 100);
  };

  // 更新统计信息
  useEffect(() => {
    if (studentGrades.length > 0) {
      // 计算不计数人数
      const notCounted = studentGrades.filter(g => g.status === 'notCounted').length;
      
      // 计算不及格人数
      const failCount = studentGrades.filter(g => 
        g.status === 'fail' || (g.comprehensiveScore < 60 && g.status !== 'notCounted')
      ).length;
      
      // 计算直升人数
      const directPromotionCount = studentGrades.filter(g => g.status === 'directPromotion').length;
      
      // 计算平均分（技能和理论两科的平均）
      const validScores = studentGrades
        .filter(g => g.status !== 'notCounted' && (g.skills > 0 || g.theory > 0))
        .map(g => (g.skills + g.theory) / 2);
      const averageScore = validScores.length > 0 
        ? validScores.reduce((a, b) => a + b, 0) / validScores.length 
        : 0;
      
      // 计算升班率
      const passCount = studentGrades.filter(g => 
        g.status === 'pass' || (g.comprehensiveScore >= 60 && g.status !== 'notCounted')
      ).length;
      const totalCount = studentGrades.filter(g => g.status !== 'notCounted').length;
      const promotionRate = totalCount > 0 ? (passCount / totalCount * 100) : 0;

      // 更新表单数据
      setClassFormData(prev => ({
        ...prev,
        notCounted: notCounted,
        failCount: failCount,
        directPromotionCount: directPromotionCount,
        averageScore: parseFloat(averageScore.toFixed(2)),
        promotionRate: parseFloat(promotionRate.toFixed(2)),
        totalStudents: studentGrades.length
      }));
    }
  }, [studentGrades]);

  // 提交班级成绩表单
  const handleClassSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!classFormData.teachingPeriod || !classFormData.studySegment || !classFormData.className) {
      alert(t('fillRequiredFields'));
      return;
    }

    if (studentGrades.length === 0) {
      alert(t('importStudentGradesFirst'));
      return;
    }

    try {
      // 重新计算综合成绩（根据考试科目占比配置）
      const updatedGrades = studentGrades.map(grade => ({
        ...grade,
        comprehensiveScore: calculateComprehensiveScore(grade)
      }));

      // 计算统计信息
      const notCounted = updatedGrades.filter(g => g.status === 'notCounted').length;
      const failCount = updatedGrades.filter(g => 
        g.status === 'fail' || (g.comprehensiveScore < 60 && g.status !== 'notCounted')
      ).length;
      const directPromotionCount = updatedGrades.filter(g => g.status === 'directPromotion').length;
      
      const validScores = updatedGrades
        .filter(g => g.status !== 'notCounted' && (g.skills > 0 || g.theory > 0))
        .map(g => (g.skills + g.theory) / 2);
      const averageScore = validScores.length > 0 
        ? validScores.reduce((a, b) => a + b, 0) / validScores.length 
        : 0;
      
      const passCount = updatedGrades.filter(g => 
        g.status === 'pass' || (g.comprehensiveScore >= 60 && g.status !== 'notCounted')
      ).length;
      const totalCount = updatedGrades.filter(g => g.status !== 'notCounted').length;
      const promotionRate = totalCount > 0 ? (passCount / totalCount * 100) : 0;

      const response = await fetch(`${API_BASE}/class-grades`, {
        method: 'POST',
        headers: getAuthHeaders(),
        body: JSON.stringify({
          ...classFormData,
          examSubjects: classFormData.examSubjects.filter(subject => subject.subject.trim() !== ''),
          studentGrades: updatedGrades,
          notCounted: notCounted,
          failCount: failCount,
          directPromotionCount: directPromotionCount,
          averageScore: parseFloat(averageScore.toFixed(2)),
          promotionRate: parseFloat(promotionRate.toFixed(2)),
          totalStudents: updatedGrades.length
        })
      });

      const result = await response.json();

      if (response.ok && result.success) {
        alert(t('classGradeCreated'));
        resetClassForm();
        // 重新加载班级成绩数据（会自动国际化）
        await loadClassGrades();
      } else {
        throw new Error(result.error || result.data?.error || t('operationFailed'));
      }
    } catch (error) {
      console.error('提交班级成绩失败:', error);
      alert(error instanceof Error ? `${t('operationFailed')}: ${error.message}` : `${t('operationFailed')}，${t('retry')}`);
    }
  };


  // 获取筛选选项 - 班级从班级管理数据中获取
  const classOptions = Array.from(new Set(classes.map(cls => cls.className))).filter(Boolean);
  // 如果班级管理中没有数据，则从班级成绩数据中获取作为备选
  const classGradeClassOptions = Array.from(new Set(classGrades.map(cg => cg.className))).filter(Boolean);
  // 合并两个数据源，确保所有班级都被包含
  const allClassOptions = Array.from(new Set([...classOptions, ...classGradeClassOptions])).filter(Boolean);
  const studySegmentOptions = Array.from(new Set(classGrades.map(cg => cg.studySegment))).filter(Boolean);
  const teachingPeriodOptions = Array.from(new Set(classGrades.map(cg => cg.teachingPeriod))).filter(Boolean);

  if (loading) {
    return (
      <div className={styles.gradeManagementLoading}>
        <div className={styles.loadingSpinner}>{t('loading')}</div>
      </div>
    );
  }

  return (
    <div className={styles.gradeManagement}>
      <div className={styles.pageHeader}>
        <h1>{t('title')}</h1>
        <div className={styles.headerActions}>
          <button className={styles.btnPrimary} onClick={handleCreateClassGrade}>
            {t('addNew')}
          </button>
        </div>
      </div>

      <div className={styles.searchOperationsBar}>
        <div className={styles.filterGroup}>
          <select 
            className={styles.filterSelect}
            value={searchFilters.type}
            onChange={(e) => setSearchFilters({...searchFilters, type: e.target.value})}
          >
            <option value="">{t('typePlaceholder')}</option>
            <option value="月考">{t('monthlyExam')}</option>
            <option value="期中">{t('midterm')}</option>
            <option value="期末">{t('final')}</option>
          </select>
          
          <select 
            className={styles.filterSelect}
            value={searchFilters.teachingPeriod}
            onChange={(e) => setSearchFilters({...searchFilters, teachingPeriod: e.target.value})}
          >
            <option value="">{t('teachingPeriodPlaceholder')}</option>
            {teachingPeriodOptions.map(period => (
              <option key={period} value={period}>{period}</option>
            ))}
          </select>
          
          <select 
            className={styles.filterSelect}
            value={searchFilters.studySegment}
            onChange={(e) => setSearchFilters({...searchFilters, studySegment: e.target.value})}
          >
            <option value="">{t('studySegmentPlaceholder')}</option>
            {studySegmentOptions.map(segment => (
              <option key={segment} value={segment}>{segment}</option>
            ))}
          </select>
          
          <select 
            className={styles.filterSelect}
            value={searchFilters.className}
            onChange={(e) => setSearchFilters({...searchFilters, className: e.target.value})}
          >
            <option value="">{t('classNamePlaceholder')}</option>
            {allClassOptions.map(className => (
              <option key={className} value={className}>{className}</option>
            ))}
          </select>
        </div>
        
        <div className={styles.operationButtons}>
          <button className={styles.btnSearch} onClick={handleSearch}>
            {t('search')}
          </button>
          <button className={styles.btnReset} onClick={handleResetSearch}>
            {t('reset')}
          </button>
        </div>
      </div>

      {/* 班级成绩列表 */}
      <div className={styles.classGradeList}>
  <table>
    <thead>
      <tr>
        <th>{t('studySegment')}</th>
        <th>{t('className')}</th>
        <th>{t('teachingPeriod')}</th>
        <th>{t('type')}</th>
        <th>{t('instructor')}</th>
        <th>{t('teacher')}</th>
        <th>{t('classroom')}</th>
        <th>{t('teachingMonth')}</th>
        <th>{t('course')}</th>
        <th>{t('totalStudents')}</th>
        <th>{t('action')}</th>
      </tr>
    </thead>
    <tbody>
      {Array.isArray(filteredClassGrades) && filteredClassGrades.length > 0 ? (
        filteredClassGrades.map((classGrade, index) => (
          <tr key={index}>
            <td>{classGrade.studySegment}</td>
            <td>{classGrade.className}</td>
            <td>{classGrade.teachingPeriod}</td>
            <td>{classGrade.type}</td>
            <td>{classGrade.instructor}</td>
            <td>{classGrade.teacher}</td>
            <td>{classGrade.classroom}</td>
            <td>{classGrade.teachingMonth}</td>
            <td>{classGrade.course}</td>
            <td>{classGrade.totalStudents}</td>
            <td>
              <button 
                className={styles.btnDetail}
                onClick={() => handleViewDetail(classGrade)}
              >
                {t('detail')}
              </button>
            </td>
          </tr>
        ))
      ) : (
        <tr>
          <td colSpan={11} className={styles.noData}>
            {t('noClassGradeData')}
          </td>
        </tr>
      )}
    </tbody>
  </table>
</div>

      {/* 班级成绩弹窗 */}
      {showClassModal && (
        <div className={styles.modalOverlay}>
          <div className={`${styles.modalContent} ${styles.largeModal}`}>
            <div className={styles.modalHeader}>
              <h2>{t('classGradeInfo')}</h2>
              <button className={styles.btnClose} onClick={resetClassForm}>×</button>
            </div>
            <form onSubmit={handleClassSubmit}>
              <div className={styles.formSection}>
                <h3>{t('classInformation')}</h3>
                <div className={styles.formRow}>
                  <div className={styles.formGroup}>
                    <label>{t('teachingPeriod')} {t('requiredField')}</label>
                    <select
                      value={classFormData.teachingPeriod}
                      onChange={(e) => setClassFormData({...classFormData, teachingPeriod: e.target.value})}
                      required
                    >
                      <option value="">{t('pleaseSelectTeachingPeriod')}</option>
                      <option value="2025.08.25-2025.09.18">{t('teachingPeriod1')}</option>
                      <option value="2025.09.18-2025.10.18">{t('teachingPeriod2')}</option>
                      <option value="2025.10.18-2025.11.18">{t('teachingPeriod3')}</option>
                      <option value="2025.11.18-2025.12.18">{t('teachingPeriod4')}</option>
                      <option value="2025.12.18-2026.01.18">{t('teachingPeriod5')}</option>
                    </select>
                  </div>
                  <div className={styles.formGroup}>
                    <label>{t('studySegment')} {t('requiredField')}</label>
                    <select
                      value={classFormData.studySegment}
                      onChange={(e) => setClassFormData({...classFormData, studySegment: e.target.value})}
                      required
                    >
                      <option value="">{t('pleaseSelect')}</option>
                      {studySegmentOptions.map(segment => (
                        <option key={segment} value={segment}>{segment}</option>
                      ))}
                    </select>
                  </div>
                </div>
                <div className={styles.formRow}>
                  <div className={styles.formGroup}>
                    <label>{t('className')} {t('requiredField')}</label>
                    <select
                      value={classFormData.className}
                      onChange={(e) => setClassFormData({...classFormData, className: e.target.value})}
                      required
                    >
                      <option value="">{t('pleaseSelectClass')}</option>
                      {allClassOptions.map(className => (
                        <option key={className} value={className}>{className}</option>
                      ))}
                    </select>
                  </div>
                  <div className={styles.formGroup}>
                    <label>{t('totalStudents')}</label>
                    <input
                      type="number"
                      value={classFormData.totalStudents}
                      readOnly
                      title={t('totalStudentsNote')}
                    />
                  </div>
                </div>
                <div className={styles.formRow}>
                  <div className={styles.formGroup}>
                    <label>{t('instructor')}</label>
                    <input
                      type="text"
                      value={classFormData.instructor}
                      onChange={(e) => setClassFormData({...classFormData, instructor: e.target.value})}
                    />
                  </div>
                  <div className={styles.formGroup}>
                    <label>{t('teacher')}</label>
                    <input
                      type="text"
                      value={classFormData.teacher}
                      onChange={(e) => setClassFormData({...classFormData, teacher: e.target.value})}
                    />
                  </div>
                </div>
                <div className={styles.formRow}>
                  <div className={styles.formGroup}>
                    <label>{t('classroom')}</label>
                    <input
                      type="text"
                      value={classFormData.classroom}
                      onChange={(e) => setClassFormData({...classFormData, classroom: e.target.value})}
                    />
                  </div>
                  <div className={styles.formGroup}>
                    <label>{t('teachingMonth')}</label>
                    <select
                      value={classFormData.teachingMonth}
                      onChange={(e) => setClassFormData({...classFormData, teachingMonth: e.target.value})}
                    >
                      <option value="">{t('pleaseSelectTeachingMonth')}</option>
                      {/* 实训选项 */}
                      <option value="实训1">{t('teachingMonthOptions.training1')}</option>
                      <option value="实训2">{t('teachingMonthOptions.training2')}</option>
                      <option value="实训3">{t('teachingMonthOptions.training3')}</option>
                      <option value="实训4">{t('teachingMonthOptions.training4')}</option>
                      <option value="实训5">{t('teachingMonthOptions.training5')}</option>
                      <option value="实训6">{t('teachingMonthOptions.training6')}</option>
                      {/* 专高选项 */}
                      <option value="专高1">{t('teachingMonthOptions.special1')}</option>
                      <option value="专高2">{t('teachingMonthOptions.special2')}</option>
                      <option value="专高3">{t('teachingMonthOptions.special3')}</option>
                      <option value="专高4">{t('teachingMonthOptions.special4')}</option>
                      <option value="专高5">{t('teachingMonthOptions.special5')}</option>
                      <option value="专高6">{t('teachingMonthOptions.special6')}</option>
                    </select>
                  </div>
                </div>
                <div className={styles.formRow}>
                  <div className={styles.formGroup}>
                    <label>{t('course')}</label>
                    <select
                      value={classFormData.course}
                      onChange={(e) => setClassFormData({...classFormData, course: e.target.value})}
                    >
                      <option value="">{t('pleaseSelectCourse')}</option>
                      {courses.map(course => (
                        <option key={course.id} value={course.name}>
                          {course.name}
                        </option>
                      ))}
                    </select>
                  </div>
                  <div className={styles.formGroup}>
                    {/* 占位 */}
                  </div>
                </div>
                <div className={styles.formRow}>
                  <div className={styles.formGroup}>
                    <label>{t('notCountedCount')}</label>
                    <input
                      type="number"
                      value={classFormData.notCounted || 0}
                      readOnly
                    />
                  </div>
                  <div className={styles.formGroup}>
                    <label>{t('directPromotionCount')}</label>
                    <input
                      type="number"
                      value={classFormData.directPromotionCount || 0}
                      readOnly
                    />
                  </div>
                </div>
                <div className={styles.formRow}>
                  <div className={styles.formGroup}>
                    <label>{t('failCount')}</label>
                    <input
                      type="number"
                      value={classFormData.failCount}
                      readOnly
                    />
                  </div>
                  <div className={styles.formGroup}>
                    <label>{t('promotionRatePercent')}</label>
                    <input
                      type="number"
                      step="0.01"
                      value={classFormData.promotionRate || 0}
                      readOnly
                    />
                  </div>
                </div>
                <div className={styles.formRow}>
                  <div className={styles.formGroup}>
                    <label>{t('averageScore')}</label>
                    <input
                      type="number"
                      step="0.01"
                      value={classFormData.averageScore}
                      readOnly
                    />
                  </div>
                  <div className={styles.formGroup}>
                    {/* 占位 */}
                  </div>
                </div>
              </div>

              <div className={styles.formSection}>
                <h3>{t('configuration')}</h3>
                <div className={styles.formRow}>
                  <div className={styles.formGroup}>
                    <label>{t('type')} {t('requiredField')}</label>
                    <select
                      value={classFormData.type}
                      onChange={(e) => setClassFormData({...classFormData, type: e.target.value})}
                      required
                    >
                      <option value="月考">{t('monthlyExam')}</option>
                      <option value="期中">{t('midterm')}</option>
                      <option value="期末">{t('final')}</option>
                    </select>
                  </div>
                  <div className={styles.formGroup}>
                    {/* 占位 */}
                  </div>
                </div>
                
                <div style={{ marginTop: '20px' }}>
                  <h4 style={{ marginBottom: '10px', fontWeight: 'bold' }}>{t('examSubjectConfig')}</h4>
                  <table className={styles.examSubjectsTable}>
                    <thead>
                      <tr>
                        <th>{t('examSubject')}</th>
                        <th>{t('writtenRatio')}</th>
                        <th>{t('examRatio')}</th>
                        <th>{t('interviewRatio')}</th>
                        <th>{t('action')}</th>
                      </tr>
                    </thead>
                    <tbody>
                      {classFormData.examSubjects.map((subject, index) => (
                        <tr key={index}>
                          <td>
                            <input
                              type="text"
                              value={subject.subject}
                              onChange={(e) => handleUpdateExamSubject(index, 'subject', e.target.value)}
                              placeholder={t('examSubjectPlaceholder')}
                              style={{ width: '100%', padding: '4px', border: '1px solid #ddd', borderRadius: '4px' }}
                            />
                          </td>
                          <td>
                            <input
                              type="number"
                              min="0"
                              max="100"
                              value={subject.writtenRatio}
                              onChange={(e) => handleUpdateExamSubject(index, 'writtenRatio', parseInt(e.target.value) || 0)}
                              style={{ width: '100%', padding: '4px', border: '1px solid #ddd', borderRadius: '4px' }}
                            />
                          </td>
                          <td>
                            <input
                              type="number"
                              min="0"
                              max="100"
                              value={subject.examRatio}
                              onChange={(e) => handleUpdateExamSubject(index, 'examRatio', parseInt(e.target.value) || 0)}
                              style={{ width: '100%', padding: '4px', border: '1px solid #ddd', borderRadius: '4px' }}
                            />
                          </td>
                          <td>
                            <input
                              type="number"
                              min="0"
                              max="100"
                              value={subject.interviewRatio}
                              onChange={(e) => handleUpdateExamSubject(index, 'interviewRatio', parseInt(e.target.value) || 0)}
                              style={{ width: '100%', padding: '4px', border: '1px solid #ddd', borderRadius: '4px' }}
                            />
                          </td>
                          <td>
                            <button
                              type="button"
                              onClick={() => handleRemoveExamSubject(index)}
                              style={{
                                padding: '4px 8px',
                                backgroundColor: '#ff4d4f',
                                color: 'white',
                                border: 'none',
                                borderRadius: '4px',
                                cursor: 'pointer'
                              }}
                            >
                              {t('delete')}
                            </button>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                  <button
                    type="button"
                    onClick={handleAddExamSubject}
                    style={{
                      marginTop: '10px',
                      padding: '6px 12px',
                      backgroundColor: '#1890ff',
                      color: 'white',
                      border: 'none',
                      borderRadius: '4px',
                      cursor: 'pointer'
                    }}
                  >
                    {t('addSubject')}
                  </button>
                </div>
              </div>

              <div className={styles.formSection}>
                <h3>{t('studentGrades')}</h3>
                <div style={{ marginBottom: '10px' }}>
                  <button
                    type="button"
                    onClick={handleImportStudentGrades}
                    className={styles.btnPrimary}
                  >
                    {t('import')}
                  </button>
                </div>
                <div style={{
                  padding: '10px',
                  backgroundColor: '#fffbe6',
                  border: '1px solid #ffe58f',
                  borderRadius: '4px',
                  marginBottom: '15px',
                  color: '#d48806'
                }}>
                  {t('noteSaveChanges')}
                </div>
                <table className={styles.examSubjectsTable} style={{ width: '100%' }}>
                  <thead>
                    <tr>
                      <th>{t('studentId')}</th>
                      <th>{t('name')}</th>
                      <th>{t('skills')}</th>
                      <th>{t('theory')}</th>
                      <th>{t('comprehensiveScore')}</th>
                      <th>{t('interview')}</th>
                      <th>{t('deduction')}</th>
                      <th>{t('status')}</th>
                      <th>{t('abnormalStatus')}</th>
                      <th>{t('remarks')}</th>
                    </tr>
                  </thead>
                  <tbody>
                    {studentGrades.length > 0 ? (
                      studentGrades.map((grade, index) => (
                        <tr key={index}>
                          <td>{grade.studentId}</td>
                          <td style={{ whiteSpace: 'nowrap', wordBreak: 'keep-all' }}>{grade.studentName}</td>
                          <td>
                            <input
                              type="number"
                              value={grade.skills}
                              onChange={(e) => {
                                const updated = [...studentGrades];
                                updated[index].skills = parseFloat(e.target.value) || 0;
                                updated[index].comprehensiveScore = calculateComprehensiveScore(updated[index]);
                                setStudentGrades(updated);
                              }}
                              style={{ width: '80px', padding: '4px', border: '1px solid #ddd', borderRadius: '4px' }}
                            />
                          </td>
                          <td>
                            <input
                              type="number"
                              value={grade.theory}
                              onChange={(e) => {
                                const updated = [...studentGrades];
                                updated[index].theory = parseFloat(e.target.value) || 0;
                                updated[index].comprehensiveScore = calculateComprehensiveScore(updated[index]);
                                setStudentGrades(updated);
                              }}
                              style={{ width: '80px', padding: '4px', border: '1px solid #ddd', borderRadius: '4px' }}
                            />
                          </td>
                          <td>{grade.comprehensiveScore.toFixed(2)}</td>
                          <td>
                            <input
                              type="number"
                              value={grade.interview}
                              onChange={(e) => {
                                const updated = [...studentGrades];
                                updated[index].interview = parseFloat(e.target.value) || 0;
                                updated[index].comprehensiveScore = calculateComprehensiveScore(updated[index]);
                                setStudentGrades(updated);
                              }}
                              style={{ width: '80px', padding: '4px', border: '1px solid #ddd', borderRadius: '4px' }}
                            />
                          </td>
                          <td>
                            <input
                              type="number"
                              value={grade.deduction}
                              onChange={(e) => {
                                const updated = [...studentGrades];
                                updated[index].deduction = parseFloat(e.target.value) || 0;
                                updated[index].comprehensiveScore = calculateComprehensiveScore(updated[index]);
                                setStudentGrades(updated);
                              }}
                              style={{ width: '80px', padding: '4px', border: '1px solid #ddd', borderRadius: '4px' }}
                            />
                          </td>
                          <td>
                            <select
                              value={grade.status}
                              onChange={(e) => {
                                const updated = [...studentGrades];
                                updated[index].status = e.target.value;
                                setStudentGrades(updated);
                              }}
                              style={{ width: '100px', padding: '4px', border: '1px solid #ddd', borderRadius: '4px' }}
                            >
                              <option value="pass">{t('pass')}</option>
                              <option value="fail">{t('fail')}</option>
                              <option value="directPromotion">{t('directPromotion')}</option>
                              <option value="notCounted">{t('notCounted')}</option>
                            </select>
                          </td>
                          <td>
                            <input
                              type="text"
                              value={grade.abnormalStatus || ''}
                              onChange={(e) => {
                                const updated = [...studentGrades];
                                updated[index].abnormalStatus = e.target.value;
                                setStudentGrades(updated);
                              }}
                              placeholder={t('abnormalStatusPlaceholder')}
                              style={{ width: '120px', padding: '4px', border: '1px solid #ddd', borderRadius: '4px' }}
                            />
                          </td>
                          <td>
                            <input
                              type="text"
                              value={grade.remarks || ''}
                              onChange={(e) => {
                                const updated = [...studentGrades];
                                updated[index].remarks = e.target.value;
                                setStudentGrades(updated);
                              }}
                              placeholder={t('remarksPlaceholder')}
                              style={{ width: '120px', padding: '4px', border: '1px solid #ddd', borderRadius: '4px' }}
                            />
                          </td>
                        </tr>
                      ))
                    ) : (
                      <tr>
                        <td colSpan={10} style={{ textAlign: 'center', padding: '20px', color: '#999' }}>
                          {t('noData')}
                        </td>
                      </tr>
                    )}
                  </tbody>
                </table>
              </div>

              <div className={styles.formActions}>
                <button type="button" className={styles.btnCancel} onClick={resetClassForm}>
                  {t('cancel')}
                </button>
                <button type="submit" className={styles.btnPrimary}>
                  {t('save')}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* 详情弹窗 */}
      {showDetailModal && selectedClass && (
        <div className={styles.modalOverlay}>
          <div className={`${styles.modalContent} ${styles.largeModal}`}>
            <div className={styles.modalHeader}>
              <h2>{t('classGradeDetail')}</h2>
              <button className={styles.btnClose} onClick={() => setShowDetailModal(false)}>×</button>
            </div>
            <div className={styles.detailContent}>
              <div className={styles.formSection}>
                <h3>{t('classInformation')}</h3>
                <div className={styles.formRow}>
                  <div className={styles.formGroup}>
                    <label>{t('teachingPeriod')}</label>
                    <input
                      type="text"
                      value={selectedClass.teachingPeriod}
                      readOnly
                    />
                  </div>
                  <div className={styles.formGroup}>
                    <label>{t('studySegment')}</label>
                    <input
                      type="text"
                      value={selectedClass.studySegment}
                      readOnly
                    />
                  </div>
                </div>
                <div className={styles.formRow}>
                  <div className={styles.formGroup}>
                    <label>{t('className')}</label>
                    <input
                      type="text"
                      value={selectedClass.className}
                      readOnly
                    />
                  </div>
                  <div className={styles.formGroup}>
                    <label>{t('type')}</label>
                    <input
                      type="text"
                      value={selectedClass.type}
                      readOnly
                    />
                  </div>
                </div>
                <div className={styles.formRow}>
                  <div className={styles.formGroup}>
                    <label>{t('instructor')}</label>
                    <input
                      type="text"
                      value={selectedClass.instructor}
                      readOnly
                    />
                  </div>
                  <div className={styles.formGroup}>
                    <label>{t('teacher')}</label>
                    <input
                      type="text"
                      value={selectedClass.teacher}
                      readOnly
                    />
                  </div>
                </div>
                <div className={styles.formRow}>
                  <div className={styles.formGroup}>
                    <label>{t('classroom')}</label>
                    <input
                      type="text"
                      value={selectedClass.classroom}
                      readOnly
                    />
                  </div>
                  <div className={styles.formGroup}>
                    <label>{t('teachingMonth')}</label>
                    <input
                      type="text"
                      value={selectedClass.teachingMonth}
                      readOnly
                    />
                  </div>
                </div>
                <div className={styles.formRow}>
                  <div className={styles.formGroup}>
                    <label>{t('course')}</label>
                    <input
                      type="text"
                      value={selectedClass.course}
                      readOnly
                    />
                  </div>
                  <div className={styles.formGroup}>
                    <label>{t('totalStudents')}</label>
                    <input
                      type="number"
                      value={selectedClass.totalStudents}
                      readOnly
                    />
                  </div>
                </div>
              </div>

              <div className={styles.formSection}>
                <h3>{t('gradeStatistics')}</h3>
                <div className={styles.formRow}>
                  <div className={styles.formGroup}>
                    <label>{t('notCountedCount')}</label>
                    <input
                      type="number"
                      value={selectedClass.notCounted || 0}
                      readOnly
                    />
                  </div>
                  <div className={styles.formGroup}>
                    <label>{t('directPromotionCount')}</label>
                    <input
                      type="number"
                      value={selectedClass.directPromotionCount || 0}
                      readOnly
                    />
                  </div>
                </div>
                <div className={styles.formRow}>
                  <div className={styles.formGroup}>
                    <label>{t('failCount')}</label>
                    <input
                      type="number"
                      value={selectedClass.failCount}
                      readOnly
                    />
                  </div>
                  <div className={styles.formGroup}>
                    <label>{t('promotionRatePercent')}</label>
                    <input
                      type="number"
                      step="0.01"
                      value={selectedClass.promotionRate || 0}
                      readOnly
                    />
                  </div>
                </div>
                <div className={styles.formRow}>
                  <div className={styles.formGroup}>
                    <label>{t('averageScore')}</label>
                    <input
                      type="number"
                      step="0.01"
                      value={selectedClass.averageScore}
                      readOnly
                    />
                  </div>
                  <div className={styles.formGroup}>
                    <label>{t('enrollmentRate')}</label>
                    <input
                      type="number"
                      value={selectedClass.enrollmentRate || 0}
                      readOnly
                    />
                  </div>
                </div>
              </div>

              {selectedClass.examSubjects && selectedClass.examSubjects.length > 0 && (
                <div className={styles.formSection}>
                  <h3>{t('examSubjectConfig')}</h3>
                  <table className={styles.examSubjectsTable}>
                    <thead>
                      <tr>
                        <th>{t('subject')}</th>
                        <th>{t('writtenRatio')}</th>
                        <th>{t('examRatio')}</th>
                        <th>{t('interviewRatio')}</th>
                      </tr>
                    </thead>
                    <tbody>
                      {selectedClass.examSubjects.map((subject, index) => (
                        <tr key={index}>
                          <td>{subject.subject}</td>
                          <td>{subject.writtenRatio}%</td>
                          <td>{subject.examRatio}%</td>
                          <td>{subject.interviewRatio}%</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              )}

              {selectedClass.studentGrades && selectedClass.studentGrades.length > 0 ? (
                <div className={styles.formSection}>
                  <h3>{t('studentGrades')}</h3>
                  <table className={styles.examSubjectsTable} style={{ width: '100%' }}>
                    <thead>
                      <tr>
                        <th>{t('studentId')}</th>
                        <th>{t('name')}</th>
                        <th>{t('skills')}</th>
                        <th>{t('theory')}</th>
                        <th>{t('comprehensiveScore')}</th>
                        <th>{t('interview')}</th>
                        <th>{t('deduction')}</th>
                        <th>{t('status')}</th>
                        <th>{t('abnormalStatus')}</th>
                        <th>{t('remarks')}</th>
                      </tr>
                    </thead>
                    <tbody>
                      {selectedClass.studentGrades.map((grade, index) => (
                        <tr key={index}>
                          <td>{grade.studentId}</td>
                          <td style={{ whiteSpace: 'nowrap', wordBreak: 'keep-all' }}>{grade.studentName}</td>
                          <td>{grade.skills}</td>
                          <td>{grade.theory}</td>
                          <td>{grade.comprehensiveScore.toFixed(2)}</td>
                          <td>{grade.interview}</td>
                          <td>{grade.deduction}</td>
                          <td>{grade.status}</td>
                          <td>{grade.abnormalStatus || '-'}</td>
                          <td>{grade.remarks || '-'}</td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              ) : (
                <div className={styles.formSection}>
                  <h3>{t('studentGrades')}</h3>
                  <div style={{ padding: '20px', textAlign: 'center', color: '#999' }}>
                    {t('noStudentGradeData')}
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      )}

    </div>
  );
};

export default GradeManagement;